<template>
  <el-dialog class="dia-style" :title="title" :visible.sync="open" :close-on-click-modal="false">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" @submit.native.prevent>
      <el-form-item label="报告名称" prop="reportName">
        <el-input v-model="formData.reportName" maxlength="50" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="报告类型" prop="templateType">
        <el-select v-model="formData.templateType" filterable @focus="setMinWidth">
          <el-option
            v-for="item in typeOptions"
            :key="item.itemVale"
            :title="item.itemLabel"
            :style="{'max-width': maxWidth + 2 + 'px'}"
            :label="item.itemLabel"
            :value="item.itemVale"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报告模板" prop="templateId">
        <el-select v-model="formData.templateId" filterable>
          <el-option v-for="item in templateOptions" :key="item.id" :label="item.templateName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="文件格式" prop="fileTypes">
        <el-checkbox-group v-model="formData.fileTypes" :min="1">
          <el-checkbox label=".html" disabled>html</el-checkbox>
          <el-checkbox label=".doc">doc</el-checkbox>
          <el-checkbox label=".pdf">pdf</el-checkbox>
          <el-checkbox label=".wps">wps</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="生成方式" prop="generateType">
        <el-radio-group v-model="formData.generateType" :disabled="disabledFlag">
          <el-radio :label="2">手动生成</el-radio>
          <el-radio :label="1">自动生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="报告时间" prop="reportTime">
        <el-select v-model="cycle" style="margin-right: 10px" @change="changeTime">
          <el-option label="近一月" value="month" />
          <el-option label="近一季度" value="quarter" />
          <el-option label="近一年" value="year" />
          <el-option label="自定义时间" value="custom" />
        </el-select>
        <el-date-picker
          v-if="cycle == 'custom'"
          v-model="formData.reportTime"
          type="daterange"
          clearable
          format="yyyy-MM-dd"
          placeholder="选择日期"
        />
        <el-input v-else v-model="timeSel" style="width: 350px;" disabled />
      </el-form-item>

      <div v-if="formData.generateType == 1">
        <el-form-item label="执行方式">
          <el-radio-group v-model="formData.execType">
            <el-radio label="1">周期性执行</el-radio>
            <el-radio label="2">定时执行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执行配置" prop="execType">
          <div v-if="formData.execType == '1'" class="flexBox">
            <span style="margin: 0 5px">每 </span>
            <el-form-item prop="cycleTime">
              <el-input-number
                v-model="formData.cycleTime"
                style="margin: 0 10px 0 0"
                controls-position="right"
                :min="1"
                :max="60"
              />
            </el-form-item>
            <el-form-item prop="cycleNode">
              <el-select v-model="formData.cycleNode" placeholder="请选择">
                <el-option
                  v-for="item in cycleNodeOption"
                  :key="item.itemVale"
                  :label="item.itemLabel"
                  :value="item.itemVale"
                />
              </el-select>
            </el-form-item>
            <span style="margin: 0 5px">执行一次</span>
          </div>
          <div v-else class="flexBox">
            <el-form-item prop="timeNode">
              <el-select v-model="formData.timeNode" style="margin: 0 10px 0 0" placeholder="请选择" prop="timeNode">
                <el-option
                  v-for="item in timeNodeOptions"
                  :key="item.itemVale"
                  :label="item.itemLabel"
                  :value="item.itemVale"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="formData.timeNode == 'weekly'" prop="day">
              <el-select
                v-model="formData.day"
                style="margin: 0 10px 0 0"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in cronWeeklyOptions"
                  :key="item.itemVale"
                  :label="item.itemLabel"
                  :value="item.itemVale"
                />
              </el-select>
              <el-select
                v-if="formData.timeNode == 'monthly'"
                v-model="formData.day"
                style="margin: 0 10px 0 0"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in monthlyOptions"
                  :key="item.itemVale"
                  :label="item.itemLabel"
                  :value="item.itemVale"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="times">
              <el-select v-model="formData.times" placeholder="请选择">
                <el-option
                  v-for="item in timesOptions"
                  :key="item.itemVale"
                  :label="item.itemLabel"
                  :value="item.itemVale"
                />
              </el-select>
            </el-form-item>
            <span style="margin: 0 5px">执行一次</span>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button v-if="configId && title === '关联配置'" @click="deleteConfig">取消关联</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  createReport,
  createReportAuto,
  queryReport,
  updateReport,
  deleteConfig
} from '@/api/reportCenter/safetyReportManagement'
import { getDictList } from '@/api/milkyway/jobScheduling'
import { getTemplateType, queryPageList as getTemplate } from '@/api/reportCenter/templateManage'

import { parseTime } from '@/utils/hongke'
export default {
  props: {
    title: {
      type: String,
      default() {
        return '标题'
      }
    }
  },
  data() {
    var validateName = (rule, value, callback) => {
      const forbiddenChars = /[\\/:*?"<>|.]/

      if (forbiddenChars.test(value)) {
        callback(new Error('模板名称中不能带有 \\/:*?"<>|.等符号'))
      } else {
        callback()
      }
    }
    return {
      // 是否显示弹出层
      open: false,
      // 表单校验
      rules: {
        reportName: [
          {
            required: true,
            message: '请输入报告名称',
            trigger: 'blur'
          },
          {
            validator: validateName,
            trigger: 'change'
          }
        ],
        templateId: [
          {
            required: true,
            message: '请选择模板',
            trigger: 'change'
          }
        ],
        reportTime: [
          {
            required: true,
            message: '请选择报告时间',
            trigger: 'change'
          }
        ],
        cycleTime: [
          {
            required: true,
            message: '请输入',
            trigger: 'change'
          }
        ],
        cycleNode: [
          {
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ],
        timeNode: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        day: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        times: [
          {
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ],
        execType: [
          {
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ]
      },
      // 时间周期
      cycle: 'month',
      // 模板类型
      typeOptions: [],
      //  模板列表
      templateOptions: [],
      // 表单列表
      formData: {},
      // 时间选择回显
      timeSel: '',
      //  配置id
      configId: '',
      //  能否修改
      disabledFlag: false,
      cycleNodeOption: [],
      timeNodeOptions: [],
      cronWeeklyOptions: [],
      timesOptions: [],
      maxWidth: null
    }
  },
  computed: {},
  watch: {
    'formData.templateType': {
      handler(newVal) {
        if (newVal) {
          this.getTemplateList(this.formData.templateType)
        }
      }
    },
    'formData.execType': {
      handler() {
        this.getConfigureObj()
      }
    }
  },
  mounted() {},
  methods: {
    // 打开对话框
    show() {
      this.open = true
      this.reset()
    },
    // 时间选择改变
    changeTime(date) {
      if (date !== 'custom') {
        // 3种时间选择
        const end = new Date()
        const start = new Date()
        switch (date) {
          case 'month':
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            break
          case 'quarter':
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)

            break
          case 'year':
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)

            break
          default:
        }
        const sTime = parseTime(start, '{y}-{m}-{d} {h}:{i}:{s}')
        const eTime = parseTime(end, '{y}-{m}-{d} {h}:{i}:{s}')
        this.timeSel = parseTime(start, '{y}年{m}月{d}日') + ' ' + '-' + ' ' + parseTime(end, '{y}年{m}月{d}日')
        this.formData.reportTime = [sTime, eTime]
        this.formData.startTime = sTime
        this.formData.endTime = eTime
      }
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          if (this.cycle !== 'custom') {
            this.formData.reportTime = `${parseTime(this.formData.startTime, '{y}年{m}月{d}日')}-${parseTime(
              this.formData.endTime,
              '{y}年{m}月{d}日'
            )}`
          } else if (this.formData.reportTime) {
            this.formData.startTime = parseTime(this.formData.reportTime[0])
            this.formData.endTime = parseTime(this.formData.reportTime[1])
            this.formData.reportTime = `${parseTime(this.formData.reportTime[0], '{y}年{m}月{d}日')}-${parseTime(
              this.formData.reportTime[1],
              '{y}年{m}月{d}日'
            )}`
          }
          this.formData.fileTypes = this.formData.fileTypes.join(',')
          if (this.title === '添加') {
            if (this.formData.generateType == 2) {
              createReport(this.formData).then((res) => {
                this.$modal.msgSuccess('添加成功')
                this.open = false
                this.$emit('handleSubmit')
              })
            } else {
              this.setCron()
              createReportAuto(this.formData).then((res) => {
                this.$modal.msgSuccess('添加成功')
                this.open = false
                this.$emit('handleSubmit')
              })
            }
          } else {
            this.setCron()
            updateReport(this.formData).then((res) => {
              this.$modal.msgSuccess('添加成功')
              this.open = false
              this.$emit('handleSubmit')
            })
          }
        }
      })
    },
    //  生成表达式
    setCron() {
      let cron
      if (this.formData.execType == '1') {
        cron = `${this.formData.cycleTime}_${this.formData.cycleNode}`
      } else {
        if (this.formData.day) {
          cron = `${this.formData.timeNode}_${this.formData.day}_${this.formData.times}`
        } else {
          cron = `${this.formData.timeNode}_${this.formData.times}`
        }
      }
      this.formData.execValue = cron
      this.templateOptions.forEach((item) => {
        if (item.id === this.formData.templateId) {
          this.formData.templateName = item.templateName
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
    },
    // 表单重置
    reset() {
      this.formData = {}
      this.formData = {
        reportName: '',
        // templateType: '',
        // templateId: '',
        fileTypes: ['.html', '.doc', '.pdf', '.wps'],
        generateType: 2,
        reportTime: '',
        startTime: '',
        endTime: '',
        execType: '1'
      }
      if (this.title === '关联配置') {
        this.getConfigureObj()
        this.getTemplateData()
        this.disabledFlag = true
      }
      this.getTypeList()
      this.disabledFlag = false
      this.changeTime('month')
    },

    /** 获取模板类型列表 */
    getTypeList() {
      getTemplateType().then((res) => {
        this.typeOptions = res && res
        const val = this.formData.templateType ? this.formData.templateType : res[0].itemVale
        this.setFormData('templateType', val)
      })
    },

    /** 根据id获取模板列表 */
    getTemplateList(type) {
      getTemplate({ templateType: type, size: 999 }).then((res) => {
        this.templateOptions = res.list.length > 0 ? res.list : []
        let val = ''
        if (this.title === '关联配置') {
          val = this.formData.templateId ? ~~this.formData.templateId : res.list.length > 0 ? res.list[0].id : ''
        } else {
          val = res.list.length > 0 ? res.list[0].id : ''
        }
        this.setFormData('templateId', val)
      })
    },

    /** formData赋值：处理响应式丢失 */
    setFormData(target, val) {
      this.$set(this.formData, target, val)
    },

    /** 关联配置或者信息 */
    getTemplateData() {
      queryReport({ id: this.configId }).then((res) => {
        this.formData = res
        this.formData.generateType = ~~this.formData.generateType
        this.formData.fileTypes = this.formData.fileTypes.split(',')
        this.cycle = 'custom'
        const _times = res.reportTime.replace(/年|月|日/g, '/').split('-')
        this.formData.reportTime = [Date.parse(_times[0]), Date.parse(_times[1])]
      })
    },

    /** 获取执行配置下拉框的数据 */
    getConfigureObj() {
      //   获取周期性执行 分钟/小时
      getDictList('cronCycle').then((res) => {
        this.cycleNodeOption = res
      })
      //   获取定期执行 每天、每月、每周
      getDictList('cronTiming').then((res) => {
        this.timeNodeOptions = res
      })
      //   每周
      getDictList('cronWeekly').then((res) => {
        this.cronWeeklyOptions = res
      })
      //  每小时
      getDictList('cronHour').then((res) => {
        this.timesOptions = res
      })
    },

    /** 删除关联配置 */
    deleteConfig() {
      this.$modal
        .confirm('是否确认取消关联？')
        .then(() => {
          deleteConfig(this.configId).then((res) => {
            this.$modal.msgSuccess('取消关联成功')
            this.open = false
            this.$emit('handleSubmit')
          })
        })
        .catch((error) => {
          console.log(error)
        })
    },

    // 设置下拉框的宽度
    setMinWidth(val) {
      //  webkit内核
      if (val.srcElement) {
        this.maxWidth = val.srcElement.clientWidth
      }
      //  火狐内核
      if (val.target) {
        this.maxWidth = val.target.clientWidth
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.flexBox {
  display: flex;
  justify-content: flex-start;
}
</style>
